﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;

namespace LifeInSharePoint.SPTwitter.WebParts.AllMessages
{
    [ToolboxItemAttribute(false)]
    public class AllMessages : WebPart
    {
        private static string TwitterList = "SPTwitter";
        private string mentions = string.Empty;
        private string[] messageSplit = null;
        private SPListItemCollection items;


        private const bool defaultShowAnonymousTweets = false;
        private bool showAnonymousTweets = defaultShowAnonymousTweets;
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [Category("Parameters")]
        [WebDisplayName("Show Anonymous Tweets")]
        [Description("")]
        public bool ShowAnonymousTweets
        {
            get { return showAnonymousTweets; }
            set { showAnonymousTweets = value; }
        }


        private const int defaultNumberOfTweets = 10;
        private int numberOfTweets = defaultNumberOfTweets;
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [Category("Parameters")]
        [WebDisplayName("Number Of Tweets to show")]
        [Description("")]
        public int NumberOfTweets
        {
            get { return numberOfTweets; }
            set { numberOfTweets = value; }
        }

        public AllMessages()
        {
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            string SiteCollectionRootUrl = SPContext.Current.Site.RootWeb.Url;
            try
            {
                using (SPWeb web = SPContext.Current.Web)
                {
                    if (web != null)
                    {
                        web.AllowUnsafeUpdates = true;

                        SPList SPTwitterList = web.Lists[TwitterList];
                        items = GetAllTweets(SPTwitterList, numberOfTweets);
                        if (items.Count > 0)
                        {
                            HtmlGenericControl wrapperTable = new HtmlGenericControl("Table");
                            wrapperTable.Attributes.Add("cellpadding", "3");
                            wrapperTable.Attributes.Add("cellspacing", "0");
                            wrapperTable.Attributes.Add("border", "0");

                            this.Controls.Add(wrapperTable);

                            foreach (SPListItem item in items)
                            {
                                HtmlGenericControl wrapperRow = new HtmlGenericControl("tr");
                                wrapperTable.Controls.Add(wrapperRow);

                                    HtmlGenericControl TableData = new HtmlGenericControl("td");
                                    TableData.Attributes.Add("width", "42");
                                    wrapperRow.Controls.Add(TableData);

                                        HtmlGenericControl WrapperDiv = new HtmlGenericControl("div");
                                        WrapperDiv.Attributes.Add("margin", "5px 5px 0px 0px");                                        
                                        TableData.Controls.Add(WrapperDiv);

                                        Image userProfileImage = new Image();
                                        userProfileImage.ImageUrl = Common.GetUserProfilePicture(item);
                                        WrapperDiv.Controls.Add(userProfileImage);

                                        ImageButton retweetImage = new ImageButton();
                                        retweetImage.ImageUrl = SiteCollectionRootUrl + "/Style Library/LifeInSharePoint/Images/retweet.png";
                                        retweetImage.Click += new ImageClickEventHandler(retweetImage_Click);
                                        //set the ID of the retweetImage to the ID of the current List Item
                                        retweetImage.ID = item.ID.ToString();
                                        WrapperDiv.Controls.Add(retweetImage);

                                    HtmlGenericControl TableDataRight = new HtmlGenericControl("td");
                                    TableDataRight.Attributes.Add("margin-left", "5px");
                                    wrapperRow.Controls.Add(TableDataRight);

                                        HtmlGenericControl WrapperDivRight = new HtmlGenericControl("div");
                                        WrapperDivRight.InnerHtml = Common.AddWebAndTwitterLinks(item["Title"].ToString()) + "<br />";
                                        TableDataRight.Controls.Add(WrapperDivRight);

                                        HtmlGenericControl WrapperDivDate = new HtmlGenericControl("div");
                                        WrapperDivDate.Attributes.Add("color", "#bdbabd");
                                        WrapperDivDate.InnerHtml = Common.GetDifferenceDate((DateTime)item["Modified"], DateTime.Now) + " by " + Common.GetUserDetails(item);
                                        TableDataRight.Controls.Add(WrapperDivDate);
                                
                                                                

                            }                            
                        }
                        else
                        {
                            HtmlGenericControl WrapperDiv = new HtmlGenericControl("div");
                            WrapperDiv.Attributes.Add("margin", "5px 5px 0px 0px");
                            WrapperDiv.InnerHtml = "<p>No Messages</p>";
                            this.Controls.Add(WrapperDiv);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HtmlGenericControl ErrorDiv = new HtmlGenericControl("div");
                ErrorDiv.Attributes.Add("margin", "5px 5px 0px 0px");
                ErrorDiv.InnerHtml = "Error Displaying Messages : " + ex.Message;
                this.Controls.Add(ErrorDiv);

            }
        }

        void retweetImage_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton currentbutton = sender as ImageButton;
            int Id = Convert.ToInt32(currentbutton.ID);
            SPListItem selectedItem = items.GetItemById(Id);
            RetweetCurrentPost(selectedItem);
        }

        private void RetweetCurrentPost(SPListItem selectedItem)
        {
                    using (SPWeb web = SPContext.Current.Web)
                    {
                        if (web != null)
                        {
                            web.AllowUnsafeUpdates = true;
                            SPList SPTwitterList = web.Lists[TwitterList];

                            SPListItem SPTwitterListItem = SPTwitterList.Items.Add();

                            SPTwitterListItem["Title"] = "RT @" + Common.GetUserDetails(selectedItem) + " " + selectedItem.DisplayName;
                            messageSplit = selectedItem.DisplayName.Split(' ');
                            foreach (string word in messageSplit)
                            {
                                if (word.StartsWith("@"))
                                {
                                    mentions += word.Replace(',', ' ') + ",";
                                }
                            }
                            SPTwitterListItem["TwitterMentions"] = mentions;
                            SPTwitterListItem.Update();
                        }
                    }
        }

        public static SPListItemCollection GetAllTweets(SPList SPTwitterList, int numberOfTweets)
        {
            SPListItemCollection items = null;
            try
            {
                SPQuery query = new SPQuery();
                query.Query = string.Format("<OrderBy><FieldRef Name='Created' Ascending='FALSE'/></OrderBy>");
                items = SPTwitterList.GetItems(query);
                query.RowLimit = (uint)numberOfTweets;
            }
            catch (Exception ex)
            {
                //Utils.LogError(ex);
            }

            return items;
        }
    }
}